#!/bin/bash

# 监控间隔(秒)
INTERVAL=5

# 初始化峰值变量
PEAK_CPU=0
PEAK_MEMORY=0
PEAK_TCP=0

# 清屏并打印表头
clear
printf "%-15s %-15s %-15s %-15s\n" "时间" "CPU使用率(%)" "内存使用(GB)" "TCP连接数"
printf "%-15s %-15s %-15s %-15s\n" "-----" "-----------" "-----------" "---------"

# 无限循环监控
while true; do
    # 获取当前时间
    CURRENT_TIME=$(date +"%H:%M:%S")
    
    # 获取CPU使用率(去掉百分号)
    CPU_USAGE=$(top -bn1 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%* id.*/\1/" | awk '{print 100 - $1}')
    
    # 获取内存使用情况(转换为GB)
    MEMORY_TOTAL=$(free -m | awk '/Mem:/ {print $2}')
    MEMORY_USED=$(free -m | awk '/Mem:/ {print $3}')
    MEMORY_USAGE_GB=$(echo "scale=2; $MEMORY_USED / 1024" | bc)
    
    # 获取TCP连接数
    TCP_CONNECTIONS=$(ss -s | awk '/^TCP:/ {print $2}')
    
    # 更新峰值数据
    if (( $(echo "$CPU_USAGE > $PEAK_CPU" | bc -l) )); then
        PEAK_CPU=$CPU_USAGE
    fi
    
    if (( $(echo "$MEMORY_USAGE_GB > $PEAK_MEMORY" | bc -l) )); then
        PEAK_MEMORY=$MEMORY_USAGE_GB
    fi
    
    if [ $TCP_CONNECTIONS -gt $PEAK_TCP ]; then
        PEAK_TCP=$TCP_CONNECTIONS
    fi
    
    # 打印当前数据和峰值数据
    printf "%-15s %-15s %-15s %-15s\n" "$CURRENT_TIME" "$CPU_USAGE" "$MEMORY_USAGE_GB" "$TCP_CONNECTIONS"
    printf "%-15s %-15s %-15s %-15s\n" "峰值:" "$PEAK_CPU" "$PEAK_MEMORY" "$PEAK_TCP"
    
    # 等待指定间隔
    sleep $INTERVAL
    
    # 清除前两行以便更新数据
    tput cuu 2
    tput ed
done